﻿using System;
using System.Collections.Generic;
using System.Web.Security;
using uForum.Businesslogic.Services;

namespace uForum.Configuration
{
	public class ConverterFactory
	{
		private readonly MembershipProvider _provider;
		private static IMemberIdConverter _converter;
		static readonly object padlock = new object();

		public ConverterFactory()
		{
			_provider = Membership.Provider;
		}

		public IMemberIdConverter GetProviderKeyConverter()
		{
			lock (padlock)
			{
				if (_converter != null)
				{
					return _converter;
				}
				else
				{
					var types = umbraco.BusinessLogic.Utils.TypeFinder.FindClassesOfType<IMemberIdConverter>(false);

					foreach (var type in types)
					{
						var converter = Activator.CreateInstance(type) as IMemberIdConverter;
						if (converter != null && converter.CanHandle(_provider))
						{
							_converter = converter;
							return converter;
						}
					}
					throw new KeyNotFoundException("Could not find a IMemberIdConverter to handle the current provider: " + _provider);
				}
			}
		}
	}
}
